package com.efuture.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

//通过代理模式进行敏感词汇的过滤
//@WebFilter("/*")
public class SensitiveWordsFilter implements Filter {
   private List<String> sensitiveWords;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       try{
           sensitiveWords = new ArrayList<>();
           ServletContext servletContext = filterConfig.getServletContext();
           String path = servletContext.getRealPath("/WEB-INF/classes/敏感词汇.txt");
           FileReader fileReader = new FileReader(path);
           BufferedReader br = new BufferedReader(fileReader);
           String line = null;
           while ((line = br.readLine())!=null){
               sensitiveWords.add(line);
           }
           System.out.println(sensitiveWords);
       }catch (Exception e){
           e.printStackTrace();
       }


    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        ServletRequest proxyServletRequest = (ServletRequest)Proxy.newProxyInstance(servletRequest.getClass().getClassLoader(), servletRequest.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(method.getName().equals("getParameter")){

                    String value = (String)method.invoke(servletRequest,args);
                    if(null!=value&&value.length()>1){
                        for(String words:sensitiveWords){
                            if(value.contains(words)){
                                value = value.replaceAll(words,"***");
                            }
                        }
                    }
                   return value;

                }else{
                    return method.invoke(servletRequest,args);
                }

            }
        });
        filterChain.doFilter(proxyServletRequest,servletResponse);

    }
}
